package com.papercutting.platform.controller;

import com.papercutting.platform.common.Result;
import com.papercutting.platform.dto.response.UserFavoriteResponse;
import com.papercutting.platform.entity.Culture;
import com.papercutting.platform.entity.News;
import com.papercutting.platform.entity.Tutorial;
import com.papercutting.platform.entity.UserFavorite;
import com.papercutting.platform.mapper.CultureMapper;
import com.papercutting.platform.mapper.NewsMapper;
import com.papercutting.platform.mapper.TutorialMapper;
import com.papercutting.platform.service.UserFavoriteService;
import com.papercutting.platform.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户收藏控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/favorite")
@RequiredArgsConstructor
public class UserFavoriteController {
    
    private final UserFavoriteService userFavoriteService;
    private final JwtUtil jwtUtil;
    private final CultureMapper cultureMapper;
    private final TutorialMapper tutorialMapper;
    private final NewsMapper newsMapper;
    
    /**
     * 获取用户收藏列表（包含完整内容信息）
     */
    @GetMapping("/list")
    public Result<List<UserFavoriteResponse>> getUserFavorites(@RequestHeader("Authorization") String authHeader) {
        log.info("获取用户收藏列表");
        
        try {
            // 从Authorization头中提取token
            String token = authHeader;
            if (authHeader.startsWith("Bearer ")) {
                token = authHeader.substring(7);
            }
            
            // 从token中解析用户ID
            Long userId = jwtUtil.getUserIdFromToken(token);
            log.info("从token解析得到的用户ID: {}", userId);
            
            if (userId == null) {
                log.error("无法从token解析用户ID");
                return Result.error("用户未登录");
            }
            
            // 获取收藏列表
            List<UserFavorite> favorites = userFavoriteService.findByUserId(userId);
            log.info("用户ID {} 的收藏列表数量: {}", userId, favorites.size());
            
            // 转换为包含内容详情的响应对象
            List<UserFavoriteResponse> responseList = new ArrayList<>();
            for (UserFavorite favorite : favorites) {
                UserFavoriteResponse response = new UserFavoriteResponse();
                response.setId(favorite.getId());
                response.setUserId(favorite.getUserId());
                response.setTargetType(favorite.getTargetType());
                response.setTargetId(favorite.getTargetId());
                response.setCreateTime(favorite.getCreateTime());
                response.setUpdateTime(favorite.getUpdateTime());
                
                // 根据类型查询关联内容
                Map<String, Object> content = new HashMap<>();
                try {
                    switch (favorite.getTargetType()) {
                        case "culture":
                            Culture culture = cultureMapper.selectById(favorite.getTargetId());
                            if (culture != null && !culture.getDeleted()) {
                                content.put("id", culture.getId());
                                content.put("title", culture.getTitle());
                                content.put("subtitle", culture.getSubtitle());
                                content.put("summary", culture.getSummary());
                                content.put("coverImage", culture.getCoverImage());
                                content.put("category", culture.getCategory());
                                content.put("viewCount", culture.getViewCount());
                                content.put("likeCount", culture.getLikeCount());
                                content.put("favoriteCount", culture.getFavoriteCount());
                            }
                            break;
                        case "tutorial":
                            Tutorial tutorial = tutorialMapper.selectById(favorite.getTargetId());
                            if (tutorial != null && !tutorial.getDeleted()) {
                                content.put("id", tutorial.getId());
                                content.put("title", tutorial.getTitle());
                                content.put("subtitle", tutorial.getSubtitle());
                                content.put("summary", tutorial.getSummary());
                                content.put("coverImage", tutorial.getCoverImage());
                                content.put("difficultyLevel", tutorial.getDifficultyLevel());
                                content.put("viewCount", tutorial.getViewCount());
                                content.put("likeCount", tutorial.getLikeCount());
                                content.put("favoriteCount", tutorial.getFavoriteCount());
                            }
                            break;
                        case "news":
                            News news = newsMapper.selectById(favorite.getTargetId());
                            if (news != null && !news.getDeleted()) {
                                content.put("id", news.getId());
                                content.put("title", news.getTitle());
                                content.put("subtitle", news.getSubtitle());
                                content.put("summary", news.getSummary());
                                content.put("coverImage", news.getCoverImage());
                                content.put("viewCount", news.getViewCount());
                                content.put("likeCount", news.getLikeCount());
                            }
                            break;
                        default:
                            log.warn("未知的收藏类型: {}", favorite.getTargetType());
                    }
                } catch (Exception e) {
                    log.error("查询收藏内容详情失败 - targetType: {}, targetId: {}", 
                            favorite.getTargetType(), favorite.getTargetId(), e);
                }
                
                response.setContent(content);
                responseList.add(response);
            }
            
            log.info("返回包含内容详情的收藏列表，数量: {}", responseList.size());
            return Result.success(responseList);
        } catch (Exception e) {
            log.error("获取收藏列表失败: ", e);
            return Result.error("获取收藏列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 添加或取消收藏
     */
    @PostMapping("/toggle")
    public Result<Map<String, Object>> toggleFavorite(
            @RequestHeader("Authorization") String authHeader,
            @RequestParam String targetType,
            @RequestParam Long targetId) {
        
        log.info("切换收藏状态: targetType={}, targetId={}", targetType, targetId);
        
        try {
            // 从Authorization头中提取token
            String token = authHeader;
            if (authHeader.startsWith("Bearer ")) {
                token = authHeader.substring(7);
            }
            
            // 从token中解析用户ID
            Long userId = jwtUtil.getUserIdFromToken(token);
            log.info("从token解析得到的用户ID: {}", userId);
            
            if (userId == null) {
                log.error("无法从token解析用户ID");
                return Result.error("用户未登录");
            }
            
            boolean isFavorited = userFavoriteService.toggleFavorite(userId, targetType, targetId);
            log.info("收藏状态切换完成，用户ID: {}, 新状态: {}", userId, isFavorited);
            
            Map<String, Object> result = new HashMap<>();
            result.put("favorited", isFavorited);
            result.put("isFavorited", isFavorited);
            result.put("message", isFavorited ? "收藏成功" : "取消收藏成功");
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("切换收藏状态失败: ", e);
            return Result.error("操作失败: " + e.getMessage());
        }
    }
    
    /**
     * 检查是否已收藏
     */
    @GetMapping("/check")
    public Result<Map<String, Object>> checkFavorite(
            @RequestHeader("Authorization") String authHeader,
            @RequestParam String targetType,
            @RequestParam Long targetId) {
        
        log.info("检查收藏状态: targetType={}, targetId={}", targetType, targetId);
        
        try {
            // 从Authorization头中提取token
            String token = authHeader;
            if (authHeader.startsWith("Bearer ")) {
                token = authHeader.substring(7);
            }
            
            // 从token中解析用户ID
            Long userId = jwtUtil.getUserIdFromToken(token);
            log.info("从token解析得到的用户ID: {}", userId);
            
            if (userId == null) {
                log.error("无法从token解析用户ID");
                return Result.error("用户未登录");
            }
            
            UserFavorite favorite = userFavoriteService.findByUserIdAndTargetTypeAndTargetId(userId, targetType, targetId);
            boolean isFavorited = favorite != null;
            
            log.info("收藏状态检查完成，用户ID: {}, 是否已收藏: {}", userId, isFavorited);
            
            Map<String, Object> result = new HashMap<>();
            result.put("favorited", isFavorited);
            result.put("isFavorited", isFavorited);
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("检查收藏状态失败: ", e);
            return Result.error("检查失败: " + e.getMessage());
        }
    }
}